#!/usr/bin/env python
# coding=utf-8
# 将runtime层数据写入数据库

import MySQLdb
import time
import os
import json


def runtime():
	# 连接数据库
	conn = MySQLdb.connect(
	                host='localhost',
	                port=3306,
	                user='root',
	                passwd='cnv6201',
	                db='PRESENTATION',
	                charset='utf8',
	            )
	cur = conn.cursor()

	# 将原先状态迁移到origin的table中
	cur.execute("delete from presentation_origin_isr")
	cur.execute("delete from presentation_origin_alsr")
	cur.execute("insert into presentation_origin_isr select * from presentation_now_isr")
	cur.execute("insert into presentation_origin_alsr select * from presentation_now_alsr")

	# 清空数据库中表格内的信息
	cur.execute("delete from presentation_now_isr")
	cur.execute("delete from presentation_now_alsr")

	# 打开runtime层JSON文件读取数据
	f = open('JsonFileReport/report_runtime.json', "r", encoding='UTF-8')
	data = json.load(f)

	# 向数据库中传入ISR
	heap128_addr = data['layer_info']['ISR']['heap128_addr']
	heap1kb_addr = data['layer_info']['ISR']['heap1kb_addr']
	heap100kb_addr = data['layer_info']['ISR']['heap100kb_addr']
	heap200kb_addr = data['layer_info']['ISR']['heap200kb_addr']
	heap1mb_addr = data['layer_info']['ISR']['heap1mb_addr']
	cur.execute("insert into presentation_now_isr(heap128_addr, heap1kb_addr, heap100kb_addr, heap200kb_addr, heap1mb_addr) values(%s, %s, %s, %s, %s)",
	            [heap128_addr, heap1kb_addr, heap100kb_addr, heap200kb_addr, heap1mb_addr])

	# 向数据库中传入ALSR
	data_addr = data['layer_info']['ASLR']['data_addr']
	text_addr = data['layer_info']['ASLR']['text_addr']
	stack_addr = data['layer_info']['ASLR']['stack_addr']
	bss_addr = data['layer_info']['ASLR']['bss_addr']
	cur.execute("insert into presentation_now_alsr(data_addr, text_addr, stack_addr, bss_addr) values(%s, %s, %s, %s)",
	            [data_addr, text_addr, stack_addr, bss_addr])


	f.close()
	cur.close()
	conn.commit()
	conn.close()
	print("runtime 层数据存储成功")
